import stringify from 'qs/lib/stringify';
import { Loading } from "element-ui";

/**
 * 将对象序列化成参数
 * @param {object} data
 * @param {Parameters<qs.stringify>[1]} [options]
 */
export const qsStringify = function (data, options) {
    options = { arrayFormat: 'repeat', ...options };
    return stringify(data, options);
};

/**
 * 将对象转成 formData
 * @param {{[key: string]: Val | Val[]}} data
 * @param {'repeat' | 'brackets' | 'indices'} [arrayFormat]
 */
export const toFormData = function (data, arrayFormat = 'repeat') {
    if (data instanceof FormData) return data;
    const formData = new FormData();
    _.each(data, (val, key) => {
        if (val === undefined) return;
        if (Array.isArray(val)) {
            val = val.filter(v => v !== undefined);
            val.forEach((v, i) => {
                let k = key;
                if (arrayFormat === 'brackets') k += '[]';
                else if (arrayFormat === 'indices') k += `[${i}]`;
                formData.append(k, v === null ? '' : v);
            });
        } else {
            formData.append(key, val === null ? '' : val);
        }
    });
    return formData;
};


/**
 * 生成uuid
 * @returns
 */
export const uuid = function () {
    let s = [];
    let hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-';
    return s.join('');
};

// 移动到指定的位置和高度
export function flyto(longitude, latitude, height, earth, time = 2) {
    let option = {
        point: {
            longitude: longitude,
            latitude: latitude,
            height: height
        },
        time: time
    };
    earth.flyToTarget(option);
}
/**
 * 下载
 * */
export const downloadFile = (respose, filename = '') => {
    const blob = new Blob([respose], {
        type: "application/octet-stream",
    });
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = `${filename}.txt`;
    link.click();
};
export const windowOpen = (url, fileName = '', data, headerToken, method = 'GET') => {
    const loading = Loading.service({
        target: '#z-main',
        lock: true,
        text: 'Loading',
        background: "rgba(0, 0, 0, 0.7)",
        customClass: 'create-isLoading',
    });
    const xhr = new XMLHttpRequest();
    xhr.open(method, url, true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Authorization', headerToken);
    if (method === 'POST') {
        xhr.setRequestHeader('content-type', 'application/json');
    }

    xhr.onload = function (res) {
        if (this.status === 200) {
            const type = xhr.getResponseHeader('Content-Type');
            let fileNameHeader = xhr.getResponseHeader('Content-Disposition');
            if (fileNameHeader) {
                fileNameHeader = window.decodeURI(fileNameHeader.split('=')[1]);
                fileNameHeader = fileNameHeader.substring(
                  0,
                  fileNameHeader.indexOf(';') < 0 ? fileNameHeader.length : fileNameHeader.indexOf(';')
                );
            }
            fileName = fileNameHeader || fileName;
            const content = xhr.response;
            const blob = new Blob([content]);
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.style.display = 'none';
            link.href = url;
            link.setAttribute('download', fileName);
            document.body.appendChild(link);
            link.click();
            loading.close();
            document.body.removeChild(link); // 下载完成移除元素
            window.URL.revokeObjectURL(url); // 释放掉blob对象
        }
    };
    if (method == 'GET') {
        xhr.send();
    } else {
        xhr.send(JSON.stringify(data));
    }
};
